const db = require('../config/db');

// 获取所有房间
exports.getAllRooms = async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM Rooms');
        res.json(rows);
    } catch (err) {
        console.error('获取房间列表错误:', err);
        res.status(500).json({ error: '获取房间列表失败' });
    }
};

// 获取可用房间 (保留一个版本)
exports.getAvailableRooms = async (req, res) => {
    try {
        const [rows] = await db.query('SELECT room_id, room_number, room_type, price FROM Rooms WHERE status = "空闲"');
        res.status(200).json(rows);
    } catch (err) {
        console.error('获取可用房间错误:', err);
        res.status(500).json({ error: '获取可用房间失败', details: err.message });
    }
};

// 添加房间
exports.addRoom = async (req, res) => {
    try {
        const { room_number, room_type, beds, price } = req.body;

        // 检查房间号是否已存在
        const [existingRoom] = await db.query(
            'SELECT * FROM Rooms WHERE room_number = ?',
            [room_number]
        );

        if (existingRoom.length > 0) {
            return res.status(400).json({
                error: '房间号冲突',
                message: `房间号 ${room_number} 已被其他房间使用，请更改。`
            });
        }

        const [result] = await db.query(
            'INSERT INTO Rooms (room_number, room_type, beds, price, status) VALUES (?, ?, ?, ?, "空闲")',
            [room_number, room_type, beds, price]
        );

        res.status(201).json({ message: '房间添加成功', roomId: result.insertId });
    } catch (err) {
        console.error('添加房间错误:', err);
        res.status(500).json({ error: '添加房间失败', details: err.message });
    }
};

// 更新房间
exports.updateRoom = async (req, res) => {
    try {
        const { id } = req.params; // room_id
        const { room_number, room_type, beds, price, status } = req.body;

        // 检查新的房间号是否与其它现有房间冲突 (排除当前编辑的房间)
        const [existingRoomWithSameNumber] = await db.query(
            'SELECT * FROM Rooms WHERE room_number = ? AND room_id != ?',
            [room_number, id]
        );

        if (existingRoomWithSameNumber.length > 0) {
            return res.status(400).json({
                error: '房间号冲突',
                message: `房间号 ${room_number} 已被其他房间使用，请更改。`
            });
        }

        const query = 'UPDATE Rooms SET room_number = ?, room_type = ?, beds = ?, price = ?, status = ? WHERE room_id = ?';
        const [result] = await db.query(query, [room_number, room_type, beds, price, status, id]);

        if (result.affectedRows === 0) {
            // 如果affectedRows为0，可能是ID不存在，或者数据与现有数据相同无需更新
            return res.status(404).json({ error: '房间未找到或数据无变化，无需更新。' });
        }
        res.status(200).json({ message: '房间信息更新成功。' });

    } catch (error) {
        console.error('更新房间失败:', error);
        res.status(500).json({ error: '更新房间失败', details: error.message });
    }
};

// 删除房间 (新增此函数)
exports.deleteRoom = async (req, res) => {
    try {
        const { id } = req.params; // 获取URL中的房间ID

        // 检查房间是否正在被占用 (例如，是否有活跃的入住记录)
        const [activeCheckins] = await db.query(
            'SELECT COUNT(*) AS count FROM Checkins WHERE room_id = ? AND status = "入住中"',
            [id]
        );

        if (activeCheckins[0].count > 0) {
            return res.status(400).json({
                error: '无法删除',
                message: '该房间有正在入住的记录，请先办理退房。'
            });
        }

        const [result] = await db.query('DELETE FROM Rooms WHERE room_id = ?', [id]);

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: '房间未找到。' });
        }
        res.status(200).json({ message: '房间删除成功。' });

    } catch (error) {
        console.error('删除房间失败:', error);
        res.status(500).json({ error: '删除房间失败', details: error.message });
    }
};

// Bulk import rooms (确保此函数存在且正确)
exports.bulkImportRooms = async (req, res) => {
    try {
        const rooms = req.body; // 假设 req.body 是房间对象数组

        if (!Array.isArray(rooms) || rooms.length === 0) {
            return res.status(400).json({ error: '无效的数据', message: '导入数据应为非空数组。' });
        }

        // 提取所有要导入的房间号
        const roomNumbers = rooms.map(room => room.room_number);

        // 检查数据库中是否已存在这些房间号
        const [existingRooms] = await db.query(
            `SELECT room_number FROM Rooms WHERE room_number IN (?)`,
            [roomNumbers]
        );

        const existingRoomNumbers = existingRooms.map(room => room.room_number);
        const duplicates = rooms.filter(room => existingRoomNumbers.includes(room.room_number));

        if (duplicates.length > 0) {
            const duplicateNumbers = duplicates.map(r => r.room_number).join(', ');
            return res.status(400).json({
                error: '存在重复房间号',
                message: `以下房间号已存在: ${duplicateNumbers}`,
                duplicates
            });
        }

        // 构建批量插入的 values
        const values = rooms.map(room => [
            room.room_number,
            room.room_type,
            room.beds,
            room.price,
            '空闲' // 默认状态为 '空闲'
        ]);

        const [result] = await db.query(
            'INSERT INTO Rooms (room_number, room_type, beds, price, status) VALUES ?',
            [values]
        );

        res.status(201).json({
            message: `成功导入${result.affectedRows}个房间`,
            importedCount: result.affectedRows
        });

    } catch (err) {
        if (err.code === 'ER_DUP_ENTRY') {
            console.error('批量导入房间号冲突:', err);
            res.status(400).json({
                error: '存在重复房间号',
                message: '导入文件中包含已存在的房间号（可能是由于并发或旧数据，请检查）'
            });
        } else {
            console.error('批量导入房间错误:', err);
            res.status(500).json({ error: '批量导入房间失败', details: err.message });
        }
    }
};
